﻿// ———————————————————————–
// <copyright file="Logging.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>
// ———————————————————————–
/////////////////////////////////////////////////////////////////////////////////////////////////
// Logging.cs - "Logs Errors To The ICNET Database."
// Project: "IC.NETSOA"- "ICNETLogging"
//
// Language:    C#, .NET 4.0
// Platform:    Windows 7, VS 2010
// Author:      Don McGarry The MITRE Corporation
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)
                
using System;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.Xml.Linq;

namespace ICNETLogging
{
  /// <summary>
  /// Contains methods for logging events and storing them in the database.
  /// </summary>
  public class Logging
  {  
    /// <summary>
    /// The path to the database.
    /// </summary>
    /// <remarks> changed to private, don't think this is needed outside of tihs class MK 6/13/2011</remarks>
    private static string databaseConnectionString = "Data Source=localhost;Initial Catalog=" + "LOGGING" + ";Integrated Security=True";

    /// <summary>
    /// A code that corresponds to the status of the event.
    /// </summary>
    public enum StatusCodes 
    {
      /// <summary>
      /// The event has started.
      /// </summary>
      Started = 1, 

      /// <summary>
      /// The event is running.
      /// </summary>
      Working, 

      /// <summary>
      /// The event has finished, but had to skip some steps.
      /// </summary>
      Done_Skipped, 

      /// <summary>
      /// The event has finished without errors.
      /// </summary>
      Done_OK, 

      /// <summary>
      /// The event raised an exception.
      /// </summary>
      Done_HasError 
    }

    #region Public Methods

    /// <summary>
    /// Adds an empty entry to the database.
    /// </summary>
    /// <returns>The ID associated with the event logged.</returns>
    public static int AddLoggingEventToDB()
    {
      return AddLoggingEventToDB("0.0.0.0","none",new XElement("NoContent"));
    }

    /// <summary>
    /// Logs an event to the database.
    /// </summary>
    /// <param name="xml">The item to be logged, in XML format. </param>
    /// <returns>The ID associated with the event logged.</returns>
    public static int AddLoggingEventToDB(string senderIP, string senderURI, XElement xml)
    {
      Event newEvent = new Event();
      newEvent.Date = DateTime.Now;
      newEvent.SenderIP = senderIP;
      newEvent.URI = senderURI;
      //newEvent.SenderIP = (OperationContext.Current.IncomingMessageProperties[RemoteEndpointMessageProperty.Name] as RemoteEndpointMessageProperty).Address;
      //newEvent.URI = OperationContext.Current.IncomingMessageHeaders.To.OriginalString;
      newEvent.RecievedBody = xml;

      LoggingDAL2DataContext linqDB = new LoggingDAL2DataContext(Logging.databaseConnectionString);
      linqDB.Events.InsertOnSubmit(newEvent);
      Submit(linqDB);

      return newEvent.Id;
    }
    
    /// <summary>
    /// Logs a service to the database,
    /// </summary>
    /// <param name="eventID">The handle associated with the service.</param>
    /// <param name="serviceName">The name of the service.</param>
    /// <returns>The ID associated with the event logged.</returns>
    public static EventServiceHandle AddEventServiceToDB(int eventID, string serviceName)
    {
      ServiceStatus entry = new ServiceStatus();
      entry.Status = (int)StatusCodes.Started;
      entry.ParentEventId = eventID;
      entry.ServiceName = serviceName;

      LoggingDAL2DataContext linqDB = new LoggingDAL2DataContext(Logging.databaseConnectionString);
      linqDB.ServiceStatus.InsertOnSubmit(entry);
      Submit(linqDB);

      return new EventServiceHandle(eventID, serviceName);
    }

    /// <summary>
    /// Changes the status of a service that was previously logged to the database
    /// </summary>
    /// <param name="eventID">The handle associated with the service.</param>
    /// <param name="serviceName">The name of the service.</param>
    /// <param name="status">The new status that the event should be set to. </param>
    public static void ChangeEventServiceStatus(int eventID, string serviceName, StatusCodes status)
    {
      LoggingDAL2DataContext linqDB = new LoggingDAL2DataContext(Logging.databaseConnectionString);
      try
      {
        System.Linq.IQueryable<ServiceStatus> matchingEventService = from entry in linqDB.ServiceStatus
                                                                     where entry.ServiceName == serviceName && entry.ParentEventId == eventID
                                                                     select entry;
        matchingEventService.First<ServiceStatus>().Status = (int)status;
      }
      catch (Exception)
      {
        // it is OK for this to fail right now because not all deployments have the LOGGINGDB db deployed
      }

      Submit(linqDB);
    }

    /// <summary>
    /// Gets information about the 2nd frame on the stack so that it can be logged to the database.
    /// </summary>
    /// <returns>A string which contains the method name, line number, and file name of the 2nd frame on the stack. </returns>
    private static string GetStackLocationForWriteCaller()
    {
      StackTrace stackTrace = new StackTrace(true);
      StackFrame frame = stackTrace.GetFrame(2);

      return frame.GetMethod().Name + "  line " + frame.GetFileLineNumber() + " in" + frame.GetFileName();
    }
    #endregion
    #region Private Methods

    /// <summary>
    /// Submits changes to the database.
    /// </summary>
    /// <param name="linqDB">The database to which changes should be submitted. </param>
    private static void Submit(LoggingDAL2DataContext linqDB)
    {
      try
      {
        linqDB.SubmitChanges();
      }
      catch (Exception)
      {
        // it is OK for this to fail right now because not all deployments have the LOGGINGDB db deployed
      }
    }
    #endregion

    /// <summary>
    /// Represents an event, and contains methods to output information about features of the event.
    /// </summary>
    public class EventServiceHandle
    {
      /// <summary>
      /// The handle associated with the event.
      /// </summary>
      private int eventID;

      /// <summary>
      /// The service that caused the event.
      /// </summary>
      private string serviceName;

      /// <summary>
      /// Initializes a new instance of the EventServiceHandle class.
      /// </summary>
      /// <param name="eventID">The handle associated with the event.</param>
      /// <param name="serviceName">The service that caused the event.</param>
      public EventServiceHandle(int eventID, string serviceName)
      {
        this.eventID = eventID;
        this.serviceName = serviceName;
      }

      /// <summary>
      /// Creates an info message which contains various features about the event, and logs it to the database. 
      /// </summary>
      /// <param name="info">The content of the message.</param>
      public void WriteInfo(string info)
      {
        InfoMessage infoMsg = new InfoMessage();
        infoMsg.Date = DateTime.Now;
        infoMsg.Content = info;
        infoMsg.StackLocation = GetStackLocationForWriteCaller();
        infoMsg.ParentEventId = this.eventID;
        infoMsg.ParentServiceName = this.serviceName;

        LoggingDAL2DataContext linqDB = new LoggingDAL2DataContext(Logging.databaseConnectionString);
        linqDB.InfoMessages.InsertOnSubmit(infoMsg);
        Submit(linqDB);
      }

      /// <summary>
      /// Write an exception to the database. 
      /// </summary>
      /// <param name="exception">The exception to be written to the database.</param>
      public void WriteError(Exception exception)
      {
        ErrorMessage errorMsg = new ErrorMessage();
        errorMsg.Date = DateTime.Now;
        errorMsg.Exception = exception.ToString();
        errorMsg.ParentEventId = this.eventID;
        errorMsg.ParentServiceName = this.serviceName;

        LoggingDAL2DataContext linqDB = new LoggingDAL2DataContext(Logging.databaseConnectionString);
        linqDB.ErrorMessages.InsertOnSubmit(errorMsg);
        Submit(linqDB);
      }
    }
  }
}
